package com.example.backend.controller.cart;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.backend.dto.request.CartDto;
import com.example.backend.dto.request.PageUserDto;
import com.example.backend.entitly.mysql.user.Carts;
import com.example.backend.enums.ResultCodeEnum;
import com.example.backend.service.mysql.order.CartsService;
import com.example.backend.utils.ResultJson;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/cart")
@Tag(name = "购物车管理")
public class CartController {

    private final CartsService cartsService;

    private Integer getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            return (Integer) authentication.getPrincipal();
        }
        throw new UsernameNotFoundException(ResultCodeEnum.NOT_LOGIN.getMessage());
    }

    @Transactional
    @Operation(summary = "创建购物车", description = "创建购物车")
    @PostMapping("/create")
    public ResultJson<?> createCart(CartDto cartDto) {
        Carts carts = Convert.convert(Carts.class, cartDto);
        boolean b = cartsService.saveOrUpdate(carts);
        if (!b) {
            return ResultJson.fail(ResultCodeEnum.Cart_CREATE_FAIL.getCode(), ResultCodeEnum.Cart_CREATE_FAIL.getMessage());
        }
        return ResultJson.ok();
    }

    @Transactional
    @Operation(summary = "删除购物车", description = "删除购物车")
    @DeleteMapping("/delete")
    public ResultJson<?> deleteCart(CartDto cartDto) {
        Carts carts = Convert.convert(Carts.class, cartDto);
        boolean b = cartsService.removeById(carts);
        if (!b) {
            return ResultJson.fail(ResultCodeEnum.Cart_DELETE_FAIL.getCode(), ResultCodeEnum.Cart_DELETE_FAIL.getMessage());
        }
        return ResultJson.ok();
    }

    @Transactional
    @Operation(summary = "查询购物车", description = "查询购物车")
    @PostMapping("/query")
    public ResultJson<List<Carts>> queryCart(@RequestBody PageUserDto pageUserDto) {
        pageUserDto.setUserId(getUser());
        Page<Carts> carts = cartsService.listByCart(pageUserDto);
        return ResultJson.success(carts.getRecords());
    }
}
